<?php
namespace App\Admin\Controllers\Stocking;

use App\Importer\Stocking\Sku\SkuImporter;
use App\Jobs\Stocking\SetDates;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysICountry;
use App\Models\Basics\Transport;
use App\Models\Product\ProductClassify;
use App\Models\SsBasic\AreaSku;
use App\Models\Stocking\StockingSetDate;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class SetDateUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        return view("stocking.set-date.upload.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $areaArr = [];
            $classifyArr = [];
            $items = [];
            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $classify = $row[1] ? trim($row[1]) : '';
                $date = $row[2] ? RExcel::toDateTime(trim($row[2])) : '';
                if(!$_area || !$classify || !$date){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $area = strtoupper($_area);
                $key = $area.'_'.$classify;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!strtotime($date)){
                    $errors[$count] = $date.'格式有误';
                    continue;
                }
                if(!array_key_exists($area,$areaArr)){
                    $areaArr[$area] = SysArea::getSysAreaIdByArea($area);
                }
                $areaId = $areaArr[$area];
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                if(!array_key_exists($classify,$classifyArr)){
                    $classifyArr[$classify] = ProductClassify::getIdByTitle($classify);
                }
                $classifyId = $classifyArr[$classify];
                if(!$classifyId){
                    $errors[$count] = $classify.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $reCount = StockingSetDate::query()->where('area_id',$areaId)->where('classify_id',$classifyId)->count();
                if($reCount == 0){
                    //添加备货SetDate
                    $countryIds = SysICountry::getCountryIdsByAreaId($areaId);
                    $pCycleForSetDate = StockingSetDate::getPCycle($countryIds,$classifyId); //产品周期
                    $seaDay = Transport::getShipmentDay($areaId,1); //运输日期（天数）
                    $seaAvailable = AreaSku::getAvailable($pCycleForSetDate,$seaDay); //最快可售日期（天数）
                    $ssd = StockingSetDate::query()->create(
                        [
                            'area_id' => $areaId,
                            'classify_id' => $classifyId,
                            'purchase_cycle' => $pCycleForSetDate,
                            'sea_day' => $seaDay,
                            'sea_available' => $seaAvailable,
                            'set_date' => date('Y-m-01',strtotime($date)),
                            'status' => StockingSetDate::STATUS_NORMAL
                        ]
                    );
                    if($ssd){
                        $items[] = $ssd;
                        DB::commit();
                    }else{
                        DB::rollBack();
                    }
                }else{
                    $ssd = StockingSetDate::query()
                        ->where('area_id',$areaId)
                        ->where('classify_id',$classifyId)
                        ->first();
                    $ssd->set_date = date('Y-m-01',strtotime($date));
                    $ssd->status = StockingSetDate::setDateLe2Date($ssd->set_date,$ssd->sea_available);
                    $flag = $ssd->save();
                    if($flag){
                        $items[] = $ssd;
                        DB::commit();
                    }else{
                        DB::rollBack();
                    }
                }
            }
            if(!empty($items)){
                //回写备货设定日期(批量操作)
                SetDates::dispatch($items);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
